<template>
  <div class="hawkContent">
    <hawk-breadcrumb></hawk-breadcrumb>
    <el-row :gutter="20">
      <el-col :span="3">
        <el-input placeholder="请输入模板名称搜索" v-model="queryForm.query.host">
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="hawkSearch" @click="init">搜索</el-button>
        <el-button plain @click="reSet">重置</el-button>
      </el-col>
      <el-col :span="4"
              style="float: right; text-align: right; padding-right: 30px">
        <el-col :span="4"
                style="float: right; text-align: right; padding-right: 30px; margin-right: 50px">
          <el-button type="hawkCreate" @click='editTemplate'>创建模板</el-button>
        </el-col>

      </el-col>
    </el-row>
    <!-- @selectionChange="handleSelectionChange" -->
    <hawk-table :table-data="tableData" :number="true"
                v-model="multipleSelection" :options="[
        { key: 'host', label: '名称', width: '200' },
        { key: 'name', label: '别名', width: '200' },
        { key: 'itemCount', label: '监控项数量', width: '100' },
        { key: 'triggerCount', label: '触发器数量' },
        { key: 'handle', label: '操作', width: '180' },
      ]">

      <template #templates="{ row }">
        <span>{{ row.templateNames.join('，') }}</span>
      </template>
      <template #itemCount="{ row }">
        <span>{{ !row.itemCount?'0': row.itemCount }}</span>
      </template>
      <template #triggerCount="{ row }">
        <span class="triggerCount"
              @click="goViewTiggers(row)">{{ row.triggerCount }}</span>
      </template>
      <template #handle="{ row }">
        <div v-if="!row.description">
          <span class="hawk-text-btn" @click="editTemplate(row)"
                v-if="!row.readOnly">编辑</span>
          <!-- <span class="hawk-text-divider" v-if="!row.readOnly">|</span>
        <span class="hawk-text-btn" @click="cloneUser(row)">克隆</span> -->
          <span class="hawk-text-divider" v-if="!row.readOnly">|</span>
          <span class="hawk-text-btn" @click="delUser(row)"
                v-if="!row.readOnly">删除</span>
        </div>
        <div v-else>默认模板</div>
      </template>
    </hawk-table>

    <el-dialog :title="formTitle" :visible.sync="addDialogVisible" width="30%"
               :close-on-click-modal="false" @close="addDialogClosed">

      <!-- 内容主题区 -->
      <div style="padding-right:100px">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef"
                 label-width="120px">

          <el-form-item label="模板名称" prop="host">
            <el-input v-model="addForm.host" placeholder="必须是英文和数字"></el-input>
          </el-form-item>

          <el-form-item label="模板别名" prop="name">
            <el-input v-model="addForm.name" placeholder="可以是中文，不能有特殊字符">
            </el-input>
          </el-form-item>

          <el-form-item label="选择父模板" prop="parentid">
            <el-select clearable v-model="addForm.parentid"
                       placeholder="请选择主机类型">

              <el-option v-for="item in this.tableData" :key="item.templateid"
                         :label="item.name" :value="item.templateid">
              </el-option>

            </el-select>
          </el-form-item>

        </el-form>

      </div>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>

    </el-dialog>

    <div class='bottom-btns'>
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click='multiDel'>批量删除</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryForm.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryForm.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div>

    <!-- <template-info ref="info"></template-info>
    <template-add ref="add" @init="init"></template-add> -->
  </div>
</template>
<script type="text/javascript">
/*
 * @author 宋辉辉
 * @description 模板的视图层
 * @api /template
 * @since 2021-11-02 13:52:15
 * @update 2021-11-02 13:52:29
 * @modifier 王洪展
 * @bug 无
 * @version v1.0.0
 */
import { getList, doEdit, doAdd, doDelete } from '@/api/monitor/config/template'
// import templateInfo from './component/templateInfo'
// import templateAdd from './component/templateAdd.vue'

//import引入的组件需要注入到对象中才能使用",
export default {
  // components: { templateAdd, templateInfo },
  data () {


    let inHaveName = (rule, value, callback) => {


      let find = this.tableData.find(el => {
        return el.host == value
      })
      console.log(find);
      if (find) {
        callback(new Error('名称已经存在'))
      } else {
        callback()
      }

    }

    return {
      formTitle: '创建模板',
      addDialogVisible: false,
      multipleSelection: [],

      addForm: {
        host: '',
        isdefault: 0, // 1 是默认模板   0  新建模板
        itemCount: '',
        name: '',
        parentid: '',

        templateid: '',
        triggerCount: '',

      },

      addFormRules: {
        host: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
          { validator: inHaveName, trigger: 'blur' },
        ],
      },

      queryForm: {
        query: {
          host: '',
        },
        page: {
          current: 1,
          size: 10,
        },
      },
      tableData: [
        // {
        //   host: "",
        //   isdefault:'',
        //   itemCount: '',
        //   name: '',
        //   parentid:'',
        //   templateid: '',
        //   triggerCount: '',

        // },
      ],
      total: 0
    }
  },
  methods: {
    reSet () {
      this.queryForm = this.$options.data().queryForm
      this.init()
    },
    handleCurrentChange (val) {
      this.queryForm.page.current = val
      this.init()
    },

    handleSizeChange (val) {
      this.queryForm.page.size = val
      this.init()
    },

    async init () {
      const res = await getList(this.queryForm)
      console.log(res);
      if (res.code == 20000) {
        this.tableData = res.data.records
        this.total = res.data.count
      }

    },
    editTemplate (row) {

      // console.log(row)
      if (row.templateid) {
        this.formTitle = '编辑模板'
        this.addForm = Object.assign({}, row)
      } else {
        // 新建模板
        this.formTitle = '新建模板'
        this.addForm = this.$options.data().addForm

      }
      this.addDialogVisible = true
    },
    // cloneUser (row) {
    //   console.log(row.templateid)
    //   if (row) {
    //     this.formTitle = '克隆模板'
    //     this.addForm = Object.assign({}, row)
    //   }
    //   this.addDialogVisible = true
    // },

    save () {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid)
        console.log(JSON.stringify(this.addForm));
        if (!valid) return

        if (this.addForm.templateid) {
          // 更新
          let ret = await doEdit(this.addForm)
          console.log(ret);


        } else {
          // 新增
          this.addForm.isdefault = 0
          let ret = await doAdd(this.addForm)
          console.log(ret);

        }
        this.addForm = this.$options.data().addForm
        this.multipleSelection = []

        this.addDialogVisible = false
        this.init()
      })
    },

    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },

    async delUser (row) {
      this.$confirm('此操作将删除该模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let ret = await doDelete([row.templateid])
          console.log(ret);
          if (ret.code == 20000) {

            let type = ''
            if (ret.data) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }

            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.tableData.length == 1) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            console.log('-------------init---');
            this.init()

          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    multiDel () {
      let list = []
      this.multipleSelection.forEach((item) => {
        list.push(item.templateid)
      })
      // console.log(list);
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          console.log(list);
          let ret = await doDelete(list)
          console.log(ret);

          if (ret.code == 20000) {

            this.$message({
              type: 'success',
              message: '删除成功!',
            })
            // console.log(this.multipleSelection.length);
            if (this.multipleSelection.length == this.tableData.length) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }
          }
          this.multipleSelection = []
          this.init()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },

  created () {
    this.init()
  }

}
</script>

<style scoped>
.itemCount {
  cursor: pointer;
  color: cadetblue;
}
</style>